Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.
In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.

The project is broken down into multiple steps:
We'll lead you through each part which you'll implement in Python.
When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.
# TODO: Make all necessary imports.
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import numpy as np
import matplotlib.pyplot as plt
import json
from PIL import Image
from pathlib import Path
import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds
tfds.disable_progress_bar()
import logging
logger = tf.get_logger()
logger.setLevel(logging.ERROR)
print('Using:')
print('\t\u2022 TensorFlow version:', tf.__version__)
print('\t\u2022 tf.keras version:', tf.keras.__version__)
print('\t\u2022 Running on GPU' if tf.test.is_gpu_available() else '\t\u2022 GPU device not found. Running on CPU')
Using: • TensorFlow version: 2.8.2 • tf.keras version: 2.8.0 • Running on GPU
2022-06-10 21:25:26.726043: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: SSE3 To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags. 2022-06-10 21:25:27.729789: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1525] Created device /device:GPU:0 with 6924 MB memory: -> device: 0, name: NVIDIA GeForce GTX 1070 Ti, pci bus id: 0000:01:00.0, compute capability: 6.1
Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.
The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.
# TODO: Load the dataset with TensorFlow Datasets.
dataset, dataset_info = tfds.load('oxford_flowers102', as_supervised=True, with_info=True)
2022-06-10 21:25:28.077164: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1525] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 6924 MB memory: -> device: 0, name: NVIDIA GeForce GTX 1070 Ti, pci bus id: 0000:01:00.0, compute capability: 6.1
# TODO: Create a training set, a validation set and a test set.
training_set, validation_set, test_set = dataset['train'], dataset['validation'], dataset['test']
# TODO: Get the number of examples in each set from the dataset info.
num_training_examples = dataset_info.splits['train'].num_examples
num_validation_examples = dataset_info.splits['validation'].num_examples
num_test_examples = dataset_info.splits['test'].num_examples
print(f'Images in the training set: {num_training_examples}')
print(f'Images in the validation set: {num_validation_examples}')
print(f'Images in the test set: {num_test_examples}')
# TODO: Get the number of classes in the dataset from the dataset info.
num_classes = dataset_info.features['label'].num_classes
print(f'There are {num_classes} classes in our dataset')
Images in the training set: 1020 Images in the validation set: 1020 Images in the test set: 6149 There are 102 classes in our dataset
# TODO: Print the shape and corresponding label of 3 images in the training set.
print('The images in the training set have:')
for image, label in training_set.take(3):
print('\n\u2022 Image dtype:', image.dtype)
print('\u2022 Image shape:', image.shape)
print('\u2022 Label dtype:', label.dtype)
The images in the training set have: • Image dtype: <dtype: 'uint8'> • Image shape: (500, 667, 3) • Label dtype: <dtype: 'int64'> • Image dtype: <dtype: 'uint8'> • Image shape: (500, 666, 3) • Label dtype: <dtype: 'int64'> • Image dtype: <dtype: 'uint8'> • Image shape: (670, 500, 3) • Label dtype: <dtype: 'int64'>
# TODO: Plot 1 image from the training set. Set the title
# of the plot to the corresponding image label.
for image, label in training_set.take(1):
image = image.numpy().squeeze()
label = label.numpy()
# Plot the image
plt.imshow(image, cmap = plt.cm.binary)
plt.colorbar()
plt.title(f'Label: {label} ({dataset_info.features["label"].names[label]})')
plt.show()
You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.
with open('label_map.json', 'r') as f:
class_names = json.load(f)
# TODO: Plot 1 image from the training set. Set the title
# of the plot to the corresponding class name.
for image, label in training_set.take(1):
image = image.numpy().squeeze()
label = label.numpy()
# Plot the image
plt.imshow(image, cmap = plt.cm.binary)
plt.colorbar()
plt.title(f'Label: {label} ({class_names[str(label+1)]})')
plt.show()
# TODO: Create a pipeline for each set.
batch_size = 32
image_size = 224
def format_image(image, label):
image = tf.cast(image, tf.float32)
image = tf.image.resize(image, (image_size, image_size))
image /= 255
return image, label
training_batches = training_set.cache().shuffle(num_training_examples//4).map(format_image).batch(batch_size).prefetch(1)
validation_batches = validation_set.cache().map(format_image).batch(batch_size).prefetch(1)
test_batches = test_set.cache().map(format_image).batch(batch_size).prefetch(1)
Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.
We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!
Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:
We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!
When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.
Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.
# TODO: Build and train your network.
# load the MobileNet pre-trained network from TensorFlow Hub
URL = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4"
feature_extractor = hub.KerasLayer(URL, input_shape=(image_size, image_size,3))
# freeze the weights and biases in our pre-trained model
feature_extractor.trainable = False
model = tf.keras.Sequential([
feature_extractor,
tf.keras.layers.Dense(num_classes, activation = 'softmax')
])
model.summary()
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
keras_layer (KerasLayer) (None, 1280) 2257984
dense (Dense) (None, 102) 130662
=================================================================
Total params: 2,388,646
Trainable params: 130,662
Non-trainable params: 2,257,984
_________________________________________________________________
# Train the classifier
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
EPOCHS = 20
history = model.fit(training_batches,
epochs=EPOCHS,
validation_data=validation_batches)
Epoch 1/20
2022-06-10 21:25:39.175751: I tensorflow/stream_executor/cuda/cuda_dnn.cc:368] Loaded cuDNN version 8100
32/32 [==============================] - 12s 192ms/step - loss: 4.2265 - accuracy: 0.1245 - val_loss: 3.0772 - val_accuracy: 0.3941 Epoch 2/20 32/32 [==============================] - 4s 120ms/step - loss: 2.0537 - accuracy: 0.6951 - val_loss: 1.9823 - val_accuracy: 0.6412 Epoch 3/20 32/32 [==============================] - 4s 119ms/step - loss: 1.0913 - accuracy: 0.9098 - val_loss: 1.5148 - val_accuracy: 0.7245 Epoch 4/20 32/32 [==============================] - 4s 114ms/step - loss: 0.6636 - accuracy: 0.9588 - val_loss: 1.2839 - val_accuracy: 0.7549 Epoch 5/20 32/32 [==============================] - 4s 114ms/step - loss: 0.4407 - accuracy: 0.9814 - val_loss: 1.1419 - val_accuracy: 0.7775 Epoch 6/20 32/32 [==============================] - 4s 116ms/step - loss: 0.3119 - accuracy: 0.9931 - val_loss: 1.0572 - val_accuracy: 0.7902 Epoch 7/20 32/32 [==============================] - 4s 117ms/step - loss: 0.2328 - accuracy: 0.9971 - val_loss: 0.9944 - val_accuracy: 0.8069 Epoch 8/20 32/32 [==============================] - 4s 111ms/step - loss: 0.1797 - accuracy: 0.9990 - val_loss: 0.9489 - val_accuracy: 0.8098 Epoch 9/20 32/32 [==============================] - 4s 119ms/step - loss: 0.1445 - accuracy: 1.0000 - val_loss: 0.9158 - val_accuracy: 0.8108 Epoch 10/20 32/32 [==============================] - 4s 119ms/step - loss: 0.1183 - accuracy: 1.0000 - val_loss: 0.8870 - val_accuracy: 0.8127 Epoch 11/20 32/32 [==============================] - 4s 114ms/step - loss: 0.0989 - accuracy: 1.0000 - val_loss: 0.8646 - val_accuracy: 0.8167 Epoch 12/20 32/32 [==============================] - 4s 117ms/step - loss: 0.0841 - accuracy: 1.0000 - val_loss: 0.8443 - val_accuracy: 0.8176 Epoch 13/20 32/32 [==============================] - 4s 115ms/step - loss: 0.0729 - accuracy: 1.0000 - val_loss: 0.8295 - val_accuracy: 0.8137 Epoch 14/20 32/32 [==============================] - 4s 118ms/step - loss: 0.0636 - accuracy: 1.0000 - val_loss: 0.8166 - val_accuracy: 0.8225 Epoch 15/20 32/32 [==============================] - 4s 123ms/step - loss: 0.0565 - accuracy: 1.0000 - val_loss: 0.8038 - val_accuracy: 0.8216 Epoch 16/20 32/32 [==============================] - 4s 115ms/step - loss: 0.0502 - accuracy: 1.0000 - val_loss: 0.7946 - val_accuracy: 0.8206 Epoch 17/20 32/32 [==============================] - 4s 120ms/step - loss: 0.0452 - accuracy: 1.0000 - val_loss: 0.7841 - val_accuracy: 0.8235 Epoch 18/20 32/32 [==============================] - 4s 115ms/step - loss: 0.0408 - accuracy: 1.0000 - val_loss: 0.7766 - val_accuracy: 0.8216 Epoch 19/20 32/32 [==============================] - 4s 116ms/step - loss: 0.0371 - accuracy: 1.0000 - val_loss: 0.7693 - val_accuracy: 0.8245 Epoch 20/20 32/32 [==============================] - 4s 121ms/step - loss: 0.0341 - accuracy: 1.0000 - val_loss: 0.7632 - val_accuracy: 0.8216
# TODO: Plot the loss and accuracy values achieved during training for the training and validation set.
training_accuracy = history.history['accuracy']
validation_accuracy = history.history['val_accuracy']
training_loss = history.history['loss']
validation_loss = history.history['val_loss']
epochs_range=range(EPOCHS)
plt.figure(figsize=(8, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, training_accuracy, label='Training Accuracy')
plt.plot(epochs_range, validation_accuracy, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(epochs_range, training_loss, label='Training Loss')
plt.plot(epochs_range, validation_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.
for image_batch, label_batch in test_batches.take(1).cache():
ps = model.predict(image_batch)
images = image_batch.numpy().squeeze()
labels = label_batch.numpy()
plt.figure(figsize=(10,15))
for n in range(30):
plt.subplot(6,5,n+1)
plt.imshow(images[n], cmap = plt.cm.binary)
color = 'green' if np.argmax(ps[n]) == labels[n] else 'red'
plt.title(class_names[str(np.argmax(ps[n])+1)], color=color)
plt.axis('off')
2022-06-10 21:27:02.848987: W tensorflow/core/kernels/data/cache_dataset_ops.cc:768] The calling iterator did not fully read the dataset being cached. In order to avoid unexpected truncation of the dataset, the partially cached contents of the dataset will be discarded. This can happen if you have an input pipeline similar to `dataset.cache().take(k).repeat()`. You should use `dataset.take(k).cache().repeat()` instead.
# TODO: Print the loss and accuracy values achieved on the entire test set.
loss, accuracy = model.evaluate(test_batches)
print('\nLoss on the TEST Set: {:,.3f}'.format(loss))
print('Accuracy on the TEST Set: {:.3%}'.format(accuracy))
193/193 [==============================] - 18s 91ms/step - loss: 0.8989 - accuracy: 0.7774 Loss on the TEST Set: 0.899 Accuracy on the TEST Set: 77.736%
Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).
# TODO: Save your trained model as a Keras model.
saved_keras_model_filepath = './prj_model.h5'
model.save(saved_keras_model_filepath)
Load the Keras model you saved above.
# TODO: Load the Keras model
reloaded_keras_model = tf.keras.models.load_model(saved_keras_model_filepath, custom_objects={'KerasLayer': hub.KerasLayer})
reloaded_keras_model.summary()
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
keras_layer (KerasLayer) (None, 1280) 2257984
dense (Dense) (None, 102) 130662
=================================================================
Total params: 2,388,646
Trainable params: 130,662
Non-trainable params: 2,257,984
_________________________________________________________________
Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:
probs, classes = predict(image_path, model, top_k)
If top_k=5 the output of the predict function should be something like this:
probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]
> ['70', '3', '45', '62', '55']
Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.
The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.
The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).
First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.
Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.
Finally, convert your image back to a NumPy array using the .numpy() method.
# TODO: Create the process_image function
def process_image(image):
"""
INPUT:
image - numpy array, image to process
OUTPUT:
image - numpy array, image with shape (224, 224, 3)
"""
image = tf.cast(image, tf.float32)
image = tf.image.resize(image, (image_size, image_size))
image /= 255
image = image.numpy()
return image
To check your process_image function we have provided 4 images in the ./test_images/ folder:
The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.
image_path = './test_images/hard-leaved_pocket_orchid.jpg'
im = Image.open(image_path)
test_image = np.asarray(im)
processed_test_image = process_image(test_image)
fig, (ax1, ax2) = plt.subplots(figsize=(10,10), ncols=2)
ax1.imshow(test_image)
ax1.set_title('Original Image')
ax2.imshow(processed_test_image)
ax2.set_title('Processed Image')
plt.tight_layout()
plt.show()
Once you can get images in the correct format, it's time to write the predict function for making inference with your model.
Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:
probs, classes = predict(image_path, model, top_k)
If top_k=5 the output of the predict function should be something like this:
probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]
> ['70', '3', '45', '62', '55']
Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.
Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.
# TODO: Create the predict function
def prepare_image(image_path):
"""
INPUT:
image_path - string, path to image file
OUTPUT:
image - numpy array, processed image with shape (224, 224, 3)
"""
image = Image.open(image_path)
image = np.asarray(image)
image = process_image(image)
return image
def predict(image_path, model, top_k):
"""
INPUT:
image_path - string, path to image file
model - object, model to make prediction
top_k - integer, number of results to return
OUTPUT:
(returns the top_k most likely class labels along with the probabilities)
probs - numpy array, probabilities
classes - list, class labels
"""
new_image = prepare_image(image_path)
new_batch = np.expand_dims(new_image, axis=0)
prediction = model.predict(new_batch)[0]
ind = np.argsort(prediction)
top_k_ind = ind[-top_k:]
probs = prediction[top_k_ind]
classes = top_k_ind + 1
classes = [class_names[str(n)] for n in classes]
return probs, classes
predict('./test_images/wild_pansy.jpg',reloaded_keras_model,5)
(array([4.9964577e-04, 6.1307097e-04, 1.7411549e-03, 1.8253865e-03,
9.9310499e-01], dtype=float32),
['clematis', 'mexican aster', 'balloon flower', 'silverbush', 'wild pansy'])
It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:
In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:

You can convert from the class integer labels to actual flower names using class_names.
# TODO: Plot the input image along with the top 5 classes
dir = './test_images'
img_files = Path(dir).glob('*.jpg')
for img_file in img_files:
probs, classes = predict(img_file, reloaded_keras_model, 5)
fig, (ax1, ax2) = plt.subplots(figsize=(9,4), ncols=2)
ax1.imshow(prepare_image(img_file), cmap = plt.cm.binary)
ax1.axis('off')
ax1.set_title(img_file)
ax2.barh(classes, probs)
ax2.set_aspect(0.3)
ax2.set_title('Class Probability')
ax2.set_xlim(0, 1.1)
plt.tight_layout()